<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Users extends CI_Controller {

	function __construct(){
		parent::__construct();
		$this->load->library('form_validation');
		$this->load->model('Users_model');
		$this->form_validation->set_error_delimiters('<div class="error"><div></div>', '</div>');
	}
		
	function index(){
		$menu=$this->_menu();
		$data['main_content'] = 'mapa.html';
		$data['menu']=$menu;
		$data['current']=-1;
		$this->load->view('includes/template', $data);
	}
	function login(){
		$menu=$this->_menu();
		$data['main_content'] = 'users/login';
		$data['menu']=$menu;
		$data['current']=-1;
		$this->load->view('includes/template', $data);
	}
	
	function register(){
		$menu=$this->_menu();
		$config = array(
			array( 'field'   => 'name', 
				   'label'   => 'Nombre', 
				   'rules'   => 'trim|required|max_length[50]|callback__alpha'
				  ),
			array( 'field'   => 'username', 
				   'label'   => 'Nombre de ususario', 
				   'rules'   => 'trim|required|alpha_dash|min_length[4]|max_length[50]|callback__username_check'
				  ),
			array( 'field'   => 'email', 
				   'label'   => 'Email', 
				   'rules'   => 'trim|required|valid_email|max_length[50]|callback__email_check'
				  ),
			array( 'field'   => 'password', 
				   'label'   => 'Contraseña', 
				   'rules'   => 'trim|required|sha1'
				  ),
			array( 'field'   => 're_password', 
				   'label'   => 'Confirmar contraseña', 
				   'rules'   => 'trim|required|matches[password]|sha1'
				  ),
			array( 'field'   => 'captcha', 
				   'label'   => 'Captcha', 
				   'rules'   => 'trim|required|callback__captcha_check'
				  ),						
			);
			

		$this->form_validation->set_rules($config);
		$this->form_validation->set_message('_username_check','El %s ya existe');
		$this->form_validation->set_message('_email_check','El %s ya existe');
		
		if ($this->form_validation->run() == FALSE){			
			$cap = $this->_captcha();
			
			$data['main_content'] = 'users/register.php';
			$data['captcha'] = $cap;
			$data['menu']=$menu;
			$data['current']=-1;
			$this->load->view('includes/template', $data);
		}
		else
		{
			$name = $this->input->post('name');
			$username = $this->input->post('username');
			$email = $this->input->post('email');
			$password = $this->input->post('password');
			$insert = $this->Users_model->insert_user($name,$username,$email,$password);
			if($insert){
			/*	$this->load->library('email');
				$config['mailtype']='html';
				$this->email->initialize($config);
				
				$this->email->from('no-reply@mimail.com', 'Aplicacion turistica');
				$this->email->to($email); 				
				$this->email->subject('Verificacion de cuenta');
				$this->email->message('Testing the email class.');	
				
				$this->email->send();
				
				echo $this->email->print_debugger();*/
				redirect('users/login');
			}
			else{
				$this->session->set_flashdata('error_register', 'No se pudo registrar como usuario');
				$data['main_content'] = 'users/register.php';
				$data['menu']=$menu;
				$data['current']=-1;
				$this->load->view('includes/template', $data);
			}
		}
	}
	
	function verify_login(){
		$username = $this->input->post('username');
		$password = sha1($this->input->post('password'));
		$login = $this->Users_model->verify_login($username,$password);
		if($login){
			$data = array (
					'is_logged_in'		=> TRUE,
					'nombre_usuario'	=>$login[0]->username,
					'nombre'			=>$login[0]->name,
					'user_id'				=>$login[0]->id,
			);
			$this->session->set_userdata($data);
			if(isset($this->session->userdata['page']))
				redirect($this->session->userdata['page']);
			else
				redirect('mapa');
		}
		else{
			$this->session->set_flashdata('error_login', 'Usuario o contraseña inválidos');
			redirect('users/login');
		}
	}
	
	function logout(){
		$this->session->sess_destroy();
		redirect('mapa');		
	}
	
	function reloadCaptcha(){
		$cap=$this->_captcha();
		echo json_encode(array('img'=>$cap['image']));
	}
	
	function _username_check($username){
		return $this->Users_model->username_check($username);
	}
	
	function _email_check($email){
		return $this->Users_model->email_check($email);
	}
	function _captcha_check($captcha){
		$this->load->model('Captcha_model');
		$this->form_validation->set_message('_captcha_check','Ingrese el codigo correcto');
		return $this->Captcha_model->check($captcha);
	}
	function _captcha(){
		$this->load->model('Captcha_model');
		$this->load->helper('captcha');
		do{			
			$vals = array(
			    'img_path'	 => './captcha/',
			    'img_url'	 => base_url().'captcha/',
			    'font_path'	 => './path/to/fonts/texb.ttf',
			    'img_width'	 => '150',
			    'img_height' => '30'
			    );
			
			$cap = create_captcha($vals);
			
			$result = $this->Captcha_model->add($cap['word'],$cap['time']);
		}while (!$result);
		
		return $cap;
	}
	function _menu(){
		$mejores = $this->_mejorPuntuacion();
		$ultimos = $this->_ultimos();
		return array(
				'mejores' =>$mejores,
				'ultimos' =>$ultimos
		);
	}
	function _mejorPuntuacion(){
		$this->load->model('Calificacion_model');	
		return $this->Calificacion_model->mejorPuntuacion();
	}
	function _ultimos(){
		$this->load->model('Places_model');
		return $this->Places_model->ultimosSitios();
	}
	function _alpha($nombre){
		$string = str_replace(" ", "", $nombre);
		return $this->form_validation->alpha($string);
	}
}
	
?>